package biz

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"

	"github.com/go-kratos/kratos/v2/log"
)

const (
	ApiKey = "de271e80bebaf5ae6998dba1e327d460"
	ApiUrl = "https://restapi.amap.com/v3/direction/driving"
)

type MapServiceBiz struct {
	log *log.Helper
}

func NewMapServiceBiz(logger log.Logger) *MapServiceBiz {
	return &MapServiceBiz{log: log.NewHelper(logger)}
}

// GetDriverInfo 获取驾驶信息
func (b *MapServiceBiz) GetDriverInfo(origin, destination string) (string, string, error) {
	parameters := fmt.Sprintf("origin=%s&destination=%s&extensions=base&output=json&key=%s", origin, destination, ApiKey)
	url := ApiUrl + "?" + parameters
	resp, err := http.Get(url)
	if err != nil {
		return "", "", err
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	body, err := io.ReadAll(resp.Body) // io.Reader
	if err != nil {
		return "", "", err
	}

	ddResp := DirectionDrivingResp{}
	if err = json.Unmarshal(body, &ddResp); err != nil {
		return "", "", err
	}

	if ddResp.Status == "0" {
		return "", "", errors.New(ddResp.Info)
	}

	path := ddResp.Route.Paths[0]
	str, _ := json.Marshal(path)
	b.log.Infof("path: %s\n", str)
	return path.Distance, path.Duration, nil
}

type DirectionDrivingResp struct {
	Status   string `json:"status,omitempty"`
	Info     string `json:"info,omitempty"`
	Infocode string `json:"infocode,omitempty"`
	Count    string `json:"count,omitempty"`
	Route    struct {
		Origin      string `json:"origin,omitempty"`
		Destination string `json:"destination,omitempty"`
		Paths       []Path `json:"paths,omitempty"`
	} `json:"route"`
}

type Path struct {
	Distance string `json:"distance,omitempty"`
	Duration string `json:"duration,omitempty"`
	Strategy string `json:"strategy,omitempty"`
}
